package com.zhongyu.user.consumer.service.impl;

import com.zhongyu.comm.pojo.Image;
import com.zhongyu.comm.pojo.User;
import com.zhongyu.comm.util.AuthException;
import com.zhongyu.comm.util.Constants;
import com.zhongyu.comm.util.MD5;
import com.zhongyu.comm.vo.TokenVo;
import com.zhongyu.user.consumer.client.ImageClient;
import com.zhongyu.user.consumer.client.UserClient;
import com.zhongyu.user.consumer.service.UserService;
import com.zhongyu.user.consumer.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("userService")
public class UserServerImpl implements UserService {

    @Resource
    private ImageClient imageClient;
    @Resource
    private UserClient userClient;

    @Override
    public Object[] searchUserVoAndToken(String phone,String password) throws AuthException {
   password= MD5.getMd5(password,32);
        User user=userClient.findOne(phone,password);
   if (user==null){
  throw new AuthException("用户名或密码错误!");
   }
  /* UserVo userVo=new UserVo();
   BeanUtils.copyProperties(user,userVo);
     Image image= imageClient.findOne(user.getId(), Constants.Image.ImageType.normal,
                Constants.Image.ImageCategory.user);
     if (image==null){
         image=new Image();
         image.setImgUrl("https://img.alicdn.com/tfs/TB1TBEJSkvoK1RjSZFNXXcxMVXa-280-280.jpg");
     }
     userVo.setUserId(user.getId());
     userVo.setImageId(image.getId());
     userVo.setImageUrl(image.getImgUrl());*/
    UserVo userVo= user2userVo(user);
      TokenVo tokenVo= userClient.getToken(user);
        return new Object[]{userVo,tokenVo};
    }

    @Override
    public UserVo searchUserByToken(String token) {
        User user=userClient.getUser(token);
      UserVo userVo=  user2userVo(user);
        return userVo;
    }

    private UserVo user2userVo(User user) {
        UserVo userVo=new UserVo();
        BeanUtils.copyProperties(user,userVo);
        Image image= imageClient.findOne(user.getId(), Constants.Image.ImageType.normal,
                Constants.Image.ImageCategory.user);
        if (image==null){
            image=new Image();
            image.setImgUrl("https://img.alicdn.com/tfs/TB1TBEJSkvoK1RjSZFNXXcxMVXa-280-280.jpg");
        }
        userVo.setUserId(user.getId());
        userVo.setImageId(image.getId());
        userVo.setImageUrl(image.getImgUrl());
        return userVo;
    }
}
